package com.gitee.empty_null.authorization.handler;

import cn.hutool.json.JSONUtil;
import com.gitee.empty_null.authorization.exception.SecurityGlobalExceptionHandler;
import com.gitee.empty_null.pojo.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author xuhainan
 * @date 2024/1/17 16:06
 * @region hefei
 */
public abstract class BaseExceptionResponseHandler implements AccessDeniedHandler, AuthenticationEntryPoint, AuthenticationFailureHandler {

    public void baseResponse(HttpServletRequest request, HttpServletResponse response, Exception authException) throws IOException {
        Result<String> result = SecurityGlobalExceptionHandler.resolveSecurityException(authException, request.getRequestURI());
        response.setContentType(MediaType.APPLICATION_JSON.toString());
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.getWriter().print(JSONUtil.toJsonStr(result));
        response.getWriter().flush();
        response.getWriter().close();
    }

}
